package com.terry.test2.new2.impl;

import com.terry.test2.Result;
import com.terry.test2.dp.*;
import com.terry.test2.new2.AccountRepository;
import com.terry.test2.new2.AccountTransferService;
import com.terry.test2.new2.AuditMessageProducer;
import com.terry.test2.new2.ExchangeRateService;
import com.terry.test2.old.TransferService;

import javax.xml.bind.ValidationException;
import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * @author 小八
 * @date 2023年02月01日11:15
 *
 *  1.抽象数据存储层 AccountRespository
 *  2.抽象第三方服务 ExchangeRateService
 *  3.抽象中间件 AuditMessageProducer
 *  4.封装业务逻辑
 */
public class TransferServiceImpl implements TransferService {

    AccountRepository accountRepository;
    ExchangeRateService exchangeRateService;
    AccountTransferService accountTransferService;
    AuditMessageProducer auditMessageProducer;

    @Override
    public Result<Boolean> transfer(Long sourceUserId, String targetAccountNumber, BigDecimal targetAmount, String targetCurrency) throws ValidationException {
        //1.校验
        Money targetMoney = new Money(targetAmount,new Currency(targetCurrency));

        //1.获取账户
        Account sourceAccount = accountRepository.find(new UserId(sourceUserId));
        Account targetAccount = accountRepository.find(new AccountNumber(targetAccountNumber));
        //2.获取汇率
        ExchangeRate exchangeRate = exchangeRateService.getExchangeRate(sourceAccount.getCurrency(), targetAccount.getCurrency());
        //3.转账
        accountTransferService.transfer(sourceAccount,targetAccount,new Money(targetAmount,new Currency(targetCurrency)),exchangeRate);
        //保存数据
        accountRepository.save(sourceAccount);
        accountRepository.save(targetAccount);

        //4.发送审计消息
        auditMessageProducer.send(AuditMessage.builder().date(LocalDateTime.now())
        .money(targetMoney).source(sourceAccount.getAccountNumber()).target(targetAccount.getAccountNumber())
        .userId(new UserId(sourceUserId)).build());

        return Result.success(true) ;
    }


}
